﻿using NcfDB.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NcfDB
{
    public partial class EditForm : Form
    {
        private string tableName;
        private string DBName;
        private bool isRow;
        public EditForm()
        {
            InitializeComponent();
        }
        public EditForm(string tableName,string DBName,bool isRow)
        {
            InitializeComponent();
            this.tableName = tableName;
            this.DBName = DBName;
            this.isRow = isRow;
        }
        
        private void EditForm_Load(object sender, EventArgs e)
        {
            this.initData();
        }
        private void initData()
        {
            if(this.isRow == true)
            {
                DataGridViewButtonColumn ButtonColumn = new DataGridViewButtonColumn();
                ButtonColumn.Name = "Delete";
                ButtonColumn.HeaderText = "操作";
                ButtonColumn.Text = "DELETE";
                ButtonColumn.UseColumnTextForButtonValue = true;
                //ButtonColumn.GetPreferredWidth()
                int i, index;
                this.Text = this.DBName + "-" + this.tableName + " 编辑行";
                Table table = new Table();
                table = CoreDBSystem.getDB(DBName).getTable(this.tableName);
                this.EditdataGridView.ColumnCount = table.fieldOrder.Count;
                this.EditdataGridView.ColumnHeadersVisible = true;
                for (i = 0; i < table.fieldOrder.Count; i++)
                {
                    this.EditdataGridView.Columns[i].Name = table.fieldOrder[i];
                }
                this.EditdataGridView.Columns.Add(ButtonColumn);
                foreach (Row row in table.Rows)
                {
                    index = this.EditdataGridView.Rows.Add();
                    for (i = 0; i < table.fieldOrder.Count; i++)
                    {
                        this.EditdataGridView.Rows[index].Cells[table.fieldOrder[i]].Value = row[table.fieldOrder[i]];
                    }
                }
            }
            else
            {
                this.EditdataGridView.AllowUserToAddRows = false;
                this.EditdataGridView.AllowUserToDeleteRows = false;
                int i, index;
                this.Text = this.DBName + "-" + this.tableName + " 编辑字段";
                Table table = new Table();
                table = CoreDBSystem.getDB(DBName).getTable(this.tableName);
                this.EditdataGridView.ColumnCount = 2;
                this.EditdataGridView.ColumnHeadersVisible = true;
                this.EditdataGridView.Columns[0].Name = "字段名";
                this.EditdataGridView.Columns[1].Name = "字段长度";
                this.EditdataGridView.Columns[0].ReadOnly = true;
                DataGridViewComboBoxColumn dcc = new DataGridViewComboBoxColumn();
                foreach (string type in Enum.GetNames(typeof(FieldType)))
                {
                    dcc.Items.Add(type);
                }
                dcc.Name = "字段类型";
                this.EditdataGridView.Columns.Add(dcc);
                DataGridViewCheckBoxColumn Keydck = new DataGridViewCheckBoxColumn();
                Keydck.Name = "主键";
                this.EditdataGridView.Columns.Add(Keydck);
                DataGridViewCheckBoxColumn Nulldck = new DataGridViewCheckBoxColumn();
                Nulldck.Name = "可为null";
                this.EditdataGridView.Columns.Add(Nulldck);
                for (i = 0; i < table.fieldOrder.Count; i++)
                {
                    index = this.EditdataGridView.Rows.Add();
                    FieldProperty fp = new FieldProperty();
                    fp = table.getFieldProperty(table.fieldOrder[i]);
                    this.EditdataGridView.Rows[index].Cells["字段名"].Value = fp.Name;
                    this.EditdataGridView.Rows[index].Cells["字段类型"].Value = fp.Type.ToString();
                    this.EditdataGridView.Rows[index].Cells["字段长度"].Value = fp.Length;
                    this.EditdataGridView.Rows[index].Cells["主键"].Value = fp.isPrimaryKey;
                    this.EditdataGridView.Rows[index].Cells["可为null"].Value = fp.acceptNull;
                }

            }
        }

        private void EditdataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (EditdataGridView.Columns[e.ColumnIndex].Name == "主键")
            {
                EditdataGridView.Rows[e.RowIndex].Cells["可为null"].Value = false;
            }
            if (EditdataGridView.Columns[e.ColumnIndex].Name == "可为null")
            {
                EditdataGridView.Rows[e.RowIndex].Cells["主键"].Value = false;
            }
            if (EditdataGridView.Columns[e.ColumnIndex].Name == "Delete" && e.RowIndex >= 0 && EditdataGridView.Rows.Count-1 > e.RowIndex) 
            {
                if (MessageBox.Show("确认删除？", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                    this.EditdataGridView.Rows.Remove(this.EditdataGridView.Rows[e.RowIndex]);
            }
        }

        private void Submitbutton_Click(object sender, EventArgs e)
        {
            if (this.isRow == true)
            {
                Table table = new Table();
                table = CoreDBSystem.getDB(DBName).getTable(this.tableName);
                while (table.Rows.Count > 0)
                {
                    table.deleteRow(table.Rows[0]);
                }
                for (int i = 0; i < this.EditdataGridView.Rows.Count - 1; i++)
                {
                    Dictionary<string, object> data = new Dictionary<string, object>();
                    for (int j = 0; j < table.FieldProperty.Count; j++)
                    {
                        data.Add(this.EditdataGridView.Columns[j].Name, this.EditdataGridView.Rows[i].Cells[j].Value);
                    }
                    Row row = new Row();
                    row.setData(data);
                    try
                    {
                        table.addRow(row);
                    }
                    catch(System.Exception exception)
                    {
                        MessageBox.Show(exception.Message);
                        return;
                    }
                }
                Program.core.save();
                this.Close();
            }
            else 
            {
                
                Table table = CoreDBSystem.getDB(DBName).getTable(this.tableName);
                for (int i = 0; i < table.FieldProperty.Count;i++ )
                {
                    FieldProperty fp = new FieldProperty();
                    fp.Name = this.EditdataGridView.Rows[i].Cells[0].Value.ToString();
                    int oldLength = table.getFieldProperty(fp.Name).Length;
                    FieldType oldType = table.getFieldProperty(fp.Name).Type;
                    FieldType newType = (FieldType)Enum.Parse(typeof(FieldType), this.EditdataGridView.Rows[i].Cells[2].Value.ToString(), true);
                    switch (newType)
                    {
                        case FieldType.Bool:
                            MessageBox.Show("不允许从" + oldType + "变更为" + newType, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        case FieldType.Char:
                            if (oldType == FieldType.Bool || oldType == FieldType.Double)
                            {
                                MessageBox.Show("不允许从" + oldType + "变更为" + newType, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                            break;
                        case FieldType.Int:
                            if (oldType == FieldType.Double || oldType == FieldType.Char)
                            {
                                MessageBox.Show("不允许从" + oldType + "变更为" + newType, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                            break;
                    }
                    foreach(Row row in table.Rows)
                    {
                        foreach(string key in row.Columns)
                        {
                            if (row[key].ToString().Length > int.Parse(this.EditdataGridView.Rows[i].Cells[1].Value.ToString()))
                            {
                                MessageBox.Show("现有数据的长度超出欲设置的字段长度", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                        }
                    }
                    table.getFieldProperty(fp.Name).Length = int.Parse(this.EditdataGridView.Rows[i].Cells[1].Value.ToString());
                    table.getFieldProperty(fp.Name).Type=(FieldType)Enum.Parse(typeof(FieldType),this.EditdataGridView.Rows[i].Cells[2].Value.ToString(), true);
                    table.getFieldProperty(fp.Name).isPrimaryKey = bool.Parse(this.EditdataGridView.Rows[i].Cells[3].Value.ToString());
                    table.getFieldProperty(fp.Name).acceptNull = bool.Parse(this.EditdataGridView.Rows[i].Cells[4].Value.ToString());
                }
                Program.core.save();
                this.Close();
            }
        }
        private void Cancelbutton_Click(object sender, EventArgs e)
        {
            this.EditdataGridView.Rows.Clear();
            this.EditdataGridView.Columns.Clear();
            this.initData();
        }

    }
}
